<template>
  <div class="logic-total">
    <div class="logic-flow-view">
      <split-pane :min-percent="20" :default-percent="70" split="vertical">
        <template slot="paneL">
          <!-- 编辑自己的代码 -->
          <div v-show="!this.$route.query.leftModel" class="left-panel">
            <LeftPanel v-if="lf" :lf="lf" :nodeList="nodeList"></LeftPanel>
          </div>

          <div class="logic-flow-view">
            <div :class="[bottomPanelBool ? 'disp' : 'dispa']">
              <!-- <div v-show="this.$route.query.leftModel" class="left-panel">
            <LeftPanel v-if="lf" :lf="lf" :nodeList="nodeList"></LeftPanel>
          </div> -->
              <div class="logic-flow-content">
                <!-- 辅助工具栏 -->
                <Control
                  class="demo-control"
                  v-if="ifFalse"
                  :lf="lf"
                  :parentTestBool="testBool"
                  @catData="$_catData"
                  @saveData="$_saveData"
                  @test="$_test"
                  @deploy="$_deploy"
                  @debugging="debugging"
                ></Control>
                <!-- 节点面板 -->
                <NodePanel v-if="lf" :lf="lf" :nodeList="nodeList"></NodePanel>
                <!-- 画布 -->
                <div class="LF-view-A">
                  <div
                    :id="[maximumWidthCanA ? 'LF-view-scrollbar' : 'LF-view']"
                    ref="container"
                  ></div>
                </div>

                <!-- 用户节点自定义操作面板 -->
                <AddPanel
                  v-if="showAddPanel"
                  class="add-panel"
                  :style="addPanelStyle"
                  :lf="lf"
                  :nodeData="addClickNode"
                  @addNodeFinish="hideAddPanel"
                >
                </AddPanel>
                <!-- 属性面板 -->
                <!-- title="设置节点属性" -->
                <el-drawer
                  :title="title"
                  :visible="dialogVisible"
                  direction="rtl"
                  :modal="false"
                  size="500px"
                  :before-close="closeDialog"
                  custom-class="nodeDrawer"
                  ref="nodeDrawer"
                  @opened="nodeOpen"
                  :wrapperClosable="false"
                >
                  <AmisRender
                    :schema="schema"
                    :data="propertyPanelData"
                    @changeProperties="changeProperties"
                  >
                  </AmisRender>
                </el-drawer>
                <!-- 流程面板 -->
                <!-- direction="btt" -->
                <!-- <el-drawer
          title="设置流程"
          :modal="false"
          :visible.sync="processDialogVisible"
          direction="rtl"
          size="500px"
        >
          <AmisRender
            :schema="processDialogSchema"
            :data="processPanelData"
            @changeProperties="changeProperties"
          >
          </AmisRender>
        </el-drawer> -->
                <el-drawer
                  title="测试"
                  :modal="false"
                  :visible.sync="testPanelVisible"
                  direction="btt"
                  size="500px"
                >
                  <!-- <PropertyDialog
              v-if="dialogVisible"
              :nodeData="clickNode"
              :lf="lf"
              @setPropertiesFinish="closeDialog"
            ></PropertyDialog> -->
                  <AmisRender
                    :schema="testPanelSchemaPattern"
                    :data="testPanelData"
                  ></AmisRender>
                </el-drawer>
                <!-- 数据查看面板 -->
                <el-dialog title="数据" :visible.sync="dataVisible" width="50%">
                  <DataDialog :graphData="graphData"></DataDialog>
                </el-dialog>
                <!-- <div>
            更多示例：
            <el-button type="text" @click="goto"
              >BpmnElement & TurboAdpter</el-button
            >
          </div> -->
              </div>
            </div>
            <div
              v-show="panelModel"
              :class="
                this.$route.query.leftModel ? 'bottom-panel' : 'bottom-panela'
              "
            >
              <BottomPanel
                :tabName="tabName"
                :schema="testPanelSchemaPattern"
                :data="testPanelData"
                ref="bottomPanel"
                @switchPanel="switchPanel"
              />
            </div>
          </div>
          <split-pane
            :min-percent="20"
            :default-percent="90"
            split="horizontal"
          >
            <template slot="paneL"> <!-- 编辑自己的代码 --></template>
            <template slot="paneR"> <!-- 编辑自己的代码 --></template>
          </split-pane>
        </template>
        <template slot="paneR">
          <!-- 编辑自己的代码 -->
          <div
            v-show="panelModel"
            :class="[
              this.$store.state.panel.rightPanelBool
                ? 'right-panel'
                : 'right-panela',
            ]"
          >
            <RightPanel
              :schema="schema"
              :data="propertyPanelData"
              :panelVisible="dialogVisible"
            />
          </div>
        </template>
      </split-pane>
    </div>
  </div>
</template>
<script>
import LogicFlow from "@logicflow/core";
// const LogicFlow = window.LogicFlow
import {
  Menu,
  Snapshot,
  MiniMap,
  InsertNodeInPolyline,
  // DndPanel,
  SelectionSelect,
} from "@logicflow/extension";
import "@logicflow/core/dist/style/index.css";
import "@logicflow/extension/lib/style/index.css";
import "@/components/style/lf.css";
import NodePanel from "./LFComponents/NodePanel";
import AddPanel from "./LFComponents/AddPanel";
import Control from "./LFComponents/Control";
import RightPanel from "./LFComponents/RightPanel";
import BottomPanel from "./LFComponents/BottomPanel";
// import PropertyDialog from './PropertySetting/PropertyDialog'
import AmisRender from "./Amis/AmisRender";
import DataDialog from "./LFComponents/DataDialog";
import { nodeList } from "./js/config.js";
import processEleSchema from "../schema/processEleSchema/index";
import { itemsStyle } from "./js/setItem.js";
import { mapMutations } from "vuex";
import {
  getSchemaById,
  updateDataById,
  deployById,
  // testDataById
} from "../services/flow";
// import 'amis/sdk/sdk'
import {
  registerStart,
  registerUser,
  registerEnd,
  registerPush,
  registerDownload,
  registerPolyline,
  registerTask,
  registerJavaClassTask,
  registerConnect,
  registerIfElse,
  registerSwitch,
} from "./registerNode";
// const demoData = require('./data.json')
const testPanelSchema = require("../schema/testPanel.json");
const processPanelSchema = require("../schema/processPanel.json");

export default {
  name: "LF",
  components: {
    NodePanel,
    AddPanel,
    Control,
    // PropertyDialog,
    DataDialog,
    AmisRender,
    RightPanel,
    BottomPanel,
  },
  data() {
    return {
      id: "",
      panelModel: true,
      rightPanelBool: true,
      bottomPanelBool: true,
      processData: {
        nodes: [],
        edges: [],
      },
      lf: null,
      showAddPanel: false,
      addPanelStyle: {
        top: 0,
        left: 0,
      },
      testBool: true,
      nodeData: null,
      addClickNode: null,
      clickNode: null,
      dialogVisible: false,
      processDialogVisible: false,
      processPanelData: {}, // 流程面板data
      propertyPanelData: null,
      graphData: null, //画布data
      processDialogSchema: null,
      testPanelSchemaPattern: {}, // 默认为对象
      testPanelVisible: false,
      testPanelData: {},
      dataVisible: false,
      config: {
        background: {
          backgroundColor: "#f7f9ff",
        },
        grid: {
          size: 10,
          visible: false,
        },
        keyboard: {
          enabled: true,
        },
        edgeTextDraggable: true,
        hoverOutline: false,
      },
      //获取节点配合，根据不同的节点变schema
      schema: {},
      moveData: {},
      nodeList,
    };
  },
  mounted() {
    this.schema = processPanelSchema; //，进入默认展示流程面板
    this.testPanelSchemaPattern = testPanelSchema; //，进入默认展示测试面板
    this.$_getProcessData();
    window.changeProperties = this.changeProperties; // 对外暴露修改流程节点属性数据的方法
    // window.changeProcessProperties = this.changeProcessProperties; // 对外暴露修改流程面板数据的方法
    this.$_getProcessPanelSchema();
  },
  methods: {
    ...mapMutations(["setRightPanelBool"]),
    $_getProcessPanelSchema() {
      this.processDialogSchema = processPanelSchema;
    },
    $_getProcessData() {
      // 地址栏有id属性的话，在这里添加上
      if ("id" in this.$route.query) {
        this.id = this.$route.query.id;
        this.testPanelData.id = this.id;
        this.testBool = false;
        this.getSchemaById(this.id);
        this.$_initLf();
      } else {
        alert("不存在id，无法使用");
      }
      if ("model" in this.$route.query && this.$route.query.model === "false") {
        this.panelModel = false;
      }
    },
    $_initLf() {
      const lf = new LogicFlow({
        ...this.config,
        grid: {
          type: "dot",
        },
        background: {
          color: "#fff",
          opacity: 0,
        },
        plugins: [
          Menu,
          MiniMap,
          Snapshot,
          InsertNodeInPolyline,
          // DndPanel,
          SelectionSelect,
        ],
        container: this.$refs.container,
      });
      // lf.setPatternItems();
      lf.openSelectionSelect();
      // lf.once("selection:selected", () => {
      //   lf.closeSelectionSelect();
      // });
      this.lf = lf;
      // 设置主题
      lf.setTheme(itemsStyle);
      this.$_registerNode();
    },
    // 自定义
    $_registerNode() {
      registerStart(this.lf);
      registerUser(this.lf);
      registerEnd(this.lf);
      registerPush(this.lf, this.clickPlus, this.mouseDownPlus);
      registerDownload(this.lf);
      registerPolyline(this.lf);
      registerTask(this.lf);
      registerJavaClassTask(this.lf);
      registerConnect(this.lf);
      registerIfElse(this.lf);
      registerSwitch(this.lf);
      this.$_render();
    },
    $_render() {
      this.lf.render(this.processData);
      this.$_LfEvent();
    },
    $_getData() {
      const data = this.lf.getGraphData();
      console.log(JSON.stringify(data));
    },
    $_reRenderProDialog(data) {
      this.schema = processEleSchema[data.type];
      this.propertyPanelData = this.lf.getProperties(data.id);
      if (data.text) {
        this.propertyPanelData.text = data.text.value;
      }
    },
    $_LfEvent() {
      // 点击节点
      this.lf.on("node:click", ({ data }) => {
        console.log("点击了节点");
        this.$_reRenderProDialog(data);
        this.$data.clickNode = data;
        if (!this.panelModel) {
          this.$data.dialogVisible = true;
        } else {
          this.setRightPanelBool(true);
        }
      });
      this.lf.on("edge:click", ({ data }) => {
        this.$data.clickNode = data;
        this.$_reRenderProDialog(data);
        if (!this.panelModel) {
          this.$data.dialogVisible = true;
        }
        // this.$data.dialogVisible = true;
      });
      this.lf.on("element:click", () => {
        this.hideAddPanel();
      });
      this.lf.on("edge:add", ({ data }) => {
        console.log("edge:add", data);
      });
      this.lf.on("node:mousemove", ({ data }) => {
        console.log("node:mousemove");
        this.moveData = data;
      });
      //   this.lf.on("blank:click", () => {
      //     this.hideAddPanel();
      //   });
      this.lf.on("connection:not-allowed", (data) => {
        this.$message({
          type: "error",
          message: data.msg,
        });
      });
      this.lf.on("node:mousemove", () => {
        console.log("on mousemove");
      });
      this.lf.on("blank:click", () => {
        if (!this.dialogVisible && !this.panelModel) {
          this.processDialogVisible = true;
        } else {
          this.schema = processPanelSchema; //在panel模式的时候将右边加入流程面板
        }
      });
    },
    clickPlus(e, attributes) {
      e.stopPropagation();
      console.log("clickPlus", e, attributes);
      const { clientX, clientY } = e;
      console.log(clientX, clientY);
      this.$data.addPanelStyle.top = clientY - 40 + "px";
      this.$data.addPanelStyle.left = clientX + "px";
      this.$data.showAddPanel = true;
      this.$data.addClickNode = attributes;
    },
    mouseDownPlus(e, attributes) {
      e.stopPropagation();
      console.log("mouseDownPlus", e, attributes);
    },
    hideAddPanel() {
      this.$data.showAddPanel = false;
      this.$data.addPanelStyle.top = 0;
      this.$data.addPanelStyle.left = 0;
      this.$data.addClickNode = null;
    },
    nodeOpen() {
      const dom =
        document.getElementsByClassName("nodeDrawer")[0].parentNode.parentNode;
      dom.style.width = "500px";
      dom.style.left = document.body.clientWidth - 500 + "px";
      console.log(screen.width, dom.style, dom, "style");
      console.log(dom);
    },
    changeProperties(data) {
      // if(data.eventType === 'submit'){
      //     return false
      // }
      if ("eventData" in data && data.eventType !== "submit") {
        if (data.eventData.id.indexOf("node") > -1) {
          this.changeNodeProperties(data);
        } else if (data.eventData.id.indexOf("panel") > -1) {
          this.changeProcessProperties(data);
        }
      }
    },
    changeNodeProperties(data) {
      const property = data.eventData.name;
      const value = data.eventData.value;
      const nodeId = this.$data.clickNode.id;
      if (property === "text") {
        //表现在在流程图上的属性
        this.lf.updateText(nodeId, value);
      } else {
        // 不显示在图上
        var obj = {};
        obj[property] = value;
        this.lf.setProperties(nodeId, obj);
      }
    },
    changeProcessProperties(data) {
      this.processPanelData[data.eventData.name] = data.eventData.value;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    closeProcessDialog() {
      this.$data.processDialogVisible = false;
    },
    $_catData() {
      this.getTotalData();
      this.$data.dataVisible = true;
    },
    $_saveData() {
      this.getTotalData();
      const obj = Object.assign({}, this.$data.graphData);
      if (this.id) {
        updateDataById(this.id, obj).then((res) => {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.editKey(res);
        });
      }
      //   else {
      //     const objStr = JSON.stringify(obj);
      //     const { processPanelData } = obj;
      //     saveData({
      //       ...processPanelData,
      //       schema: objStr,
      //     }).then((res) => {
      //       this.id = res.data.id;
      //       this.editKey(res);
      //       this.testBool = false;
      //       this.$message({
      //         type: "success",
      //         message: "保存成功",
      //       });
      //     });
      //   }
    },
    editKey(res) {
      this.key = res.data.key;
      this.testPanelData.key = this.key;
    },
    $_test() {
      console.log("点击了测试");
      if (this.$route.query.model === "false") {
        this.testPanelVisible = true;
      } else {
        this.$refs.bottomPanel.bottomPanelBool = true;
      }
      this.testPanelSchemaPattern = testPanelSchema;
      // this.testPanelVisible = true;
      //   testDataById(this.id,{}).then(res=>{
      //     console.log(res)
      //     this.$message({
      //         type: "success",
      //         message: "测试成功",
      //       });
      //   })
    },
    $_deploy() {
      deployById(this.id)
        .then((res) => {
          console.log(res, "res");
          this.$message({
            type: "success",
            message: "发布成功",
          });
        })
        .catch((error) => {
          console.log(error);
          this.$message({
            type: "error",
            message: "发布失败",
          });
        });
    },
    $_switchRight() {},
    $_switchBottom() {},
    getTotalData() {
      this.$data.graphData = this.$data.lf.getGraphData();
      this.$data.graphData.processPanelData = this.processPanelData;
      this.$data.graphData.id = this.id;
    },
    async getSchemaById() {
      await getSchemaById(this.id)
        .then((res) => {
          this.processData = res.data;
          if (
            this.processData.processPanelData !== null &&
            this.processData.processPanelData
          ) {
            // console.log(this.processData.processPanelData,'processPanelData')
            this.processPanelData = this.processData.processPanelData;
          }
          // console.log(this.processData)
          this.lf.render(this.processData);
        })
        .catch((error) => {
          console.log(error, "获取schema报错");
        });
    },
    goto() {
      this.$router.push("/TurboAdpter");
    },
  },
};
</script>
<style lang="less">
@import "../assets/style/logicPanel.less";
</style>

